package com.fastPlat.scheduled;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;

@Component
public class ScheduledMessageProducer {
	
	@Resource(name="shopProducer")
	private DefaultMQProducer shopProducer;
	
	@Value("${rocketMQ-topic}")
	private String topic;
	
	@Value("${rocketMQ-tags}")
	private String tags;
	
	@Value("${rocketMQ-producerGroup}")
	private String producerGroup;
	
	@Value("${namesrvAddr}")
	private String namesrvAddr;
	
	@PostConstruct
	private void startProducer(){
		try {
			shopProducer.setNamesrvAddr(namesrvAddr);
			shopProducer.setProducerGroup(producerGroup);
			shopProducer.start();
		} catch (MQClientException e) {
			System.out.println("shopProducer启动失败！");
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送单条信息
	 * @param message
	 * @param keys
	 * @return
	 */
	public boolean sendSingleMessage(String message,String keys){
		shopProducer.setRetryTimesWhenSendFailed(10);//失败的 情况发送10次  
		Message messageObj = new Message();
		messageObj.setTopic(topic);
		messageObj.setTags(tags);
		messageObj.setKeys(keys);
		messageObj.setBody(message.getBytes());
        // This message will be delivered to consumer 10 seconds later.
		messageObj.setDelayTimeLevel(3);
		messageObj.setWaitStoreMsgOK(true);
		try {
			// 发送消息
	        SendResult sendResult = shopProducer.send(messageObj);
	        System.out.println(sendResult.getMsgId()+",status:"+sendResult.getSendStatus());
	        return true;
		} catch (Exception e) {
			System.out.println("发送失败！");
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean sendBatchMessage(Map<String,String> messageMap ){
		shopProducer.setRetryTimesWhenSendFailed(10);//失败的 情况发送10次  
		Message messageObj = null;
		try {
			for(String key:messageMap.keySet()){
				messageObj = new Message();
				messageObj.setTopic(topic);
				messageObj.setTags(tags);
				messageObj.setKeys(key);
				messageObj.setBody(messageMap.get(key).getBytes());
				messageObj.setDelayTimeLevel(3);
				messageObj.setWaitStoreMsgOK(true);
				// 发送消息
		        SendResult sendResult = shopProducer.send(messageObj);
		        System.out.println(sendResult.getMsgId()+",status:"+sendResult.getSendStatus());
			}
			return true;
		} catch (Exception e) {
			System.out.println("发送失败！");
			e.printStackTrace();
			return false;
		}
	}
	
    @PreDestroy
    public void destroy() {
        shopProducer.shutdown();
    }
}
